package com.yhy.dubbo.service.mongo;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhy.domain.mongo.RecommendUser;
import com.yhy.domain.vo.PageResult;
import com.yhy.dubbo.api.mongo.RecommendUserApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public RecommendUser findSoulMate(Long toUserId) {
        Criteria criteria = Criteria.where("toUserId").is(toUserId);

        Query query = new Query(criteria)
                .with(Sort.by(Sort.Order.desc("score"))).limit(1);

        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    @Override
    public PageResult queryRecommendUserList(Integer page, Integer pagesize, Long toUserId) {
        //条件
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //totalCount查询
        Query countQuery = new Query(criteria);
        long count = mongoTemplate.count(countQuery, RecommendUser.class);

        //分页需要的数据查询
        Query limitQuery = new Query(criteria).skip((page-1)*pagesize).limit(pagesize);
        List<RecommendUser> recommendUserList = mongoTemplate.find(limitQuery, RecommendUser.class);

        //构建PageResult
        return new PageResult(page,pagesize, (int) count,recommendUserList);
    }

    @Override
    public RecommendUser findRecommendUser(Long userId, Long toUserId) {
        Criteria criteria = Criteria.where("toUserId").is(toUserId).and("userId").is(userId);

        RecommendUser recommendUser = mongoTemplate.findOne(new Query(criteria), RecommendUser.class);
        //1.判断 如果没有任何推荐用户 就创建假数据
        if(recommendUser == null){
            recommendUser = new RecommendUser();
            recommendUser.setScore(99d);
            recommendUser.setUserId(userId);
            recommendUser.setToUserId(toUserId);
        }
        return recommendUser;
    }
}
